package com.sky;

import org.apache.poi.xssf.usermodel.*;

import java.io.*;

public class ExcelDemo {

    public static void main(String[] args) throws IOException {
        out();
        input();

    }

    public static void out() throws IOException{
        //创建一个Excel文件对象
        XSSFWorkbook excel = new XSSFWorkbook();

        XSSFSheet sheet = excel.createSheet("book"); // 创建一个页

        XSSFRow sheetRow = sheet.createRow(0); // 在页中创建行

        // 在行中创建单元格
        sheetRow.createCell(0).setCellValue(" ");
        sheetRow.createCell(1).setCellValue("姓名");
        sheetRow.createCell(2).setCellValue("住址");

        XSSFRow sheetRow1 = sheet.createRow(1);
        sheetRow1.createCell(0).setCellValue("1");
        sheetRow1.createCell(1).setCellValue("韩立");
        sheetRow1.createCell(2).setCellValue("黄枫谷");

        XSSFRow sheetRow2 = sheet.createRow(2);
        sheetRow2.createCell(0).setCellValue("2");
        sheetRow2.createCell(1).setCellValue("叶黑");
        sheetRow2.createCell(2).setCellValue("地球");

        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\poi_excel.xlsx"));

        excel.write(fileOutputStream);

        fileOutputStream.flush();
        fileOutputStream.close();

        excel.close();
    }

    public static void input() throws IOException {
        FileInputStream fileInputStream = new FileInputStream(new File("D:\\poi_excel.xlsx"));

        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = xssfWorkbook.getSheetAt(0); // 获取 EXcel 表格第一个sheet 页

        int lastRowNum = sheet.getLastRowNum(); // 获取 sheet 页的最后一行行号

        for (int i = 0; i <= lastRowNum; i++) {

            XSSFRow sheetRow = sheet.getRow(i);

            XSSFCell rowCell0 = sheetRow.getCell(0);
            String cellValue0 = rowCell0.getStringCellValue();


            XSSFCell rowCell = sheetRow.getCell(1);
            String cellValue = rowCell.getStringCellValue();

            XSSFCell rowCell1 = sheetRow.getCell(2);
            String cellValue1 = rowCell1.getStringCellValue();

            System.out.println(cellValue0 +" " + cellValue + " " + cellValue1);

        }

        fileInputStream.close();
        xssfWorkbook.close();
    }

}
